﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using SMSROUTER.Business;
using System.Web.UI.HtmlControls;
using Utils;
using System.IO;
using Settings;
using System.Data;
using Utils;
namespace SMSROUTER.UI
{
    public partial class SmsShortCodeManagement : BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        private void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindGridData();
            pagingtop.Visible = pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                pagingtop.PageDisplay = pagingbottom.PageDisplay = 6;
                BindDropDownData();
                BindGridData();
            }
        }

        private void BindGridData()
        {
            try
            {
                int currentPage = pagingtop.CurrentPage;
                int pageSize = pagingtop.PageSize;
                int totalRecord = 0;
                int? cooperateid = ddlSearchCooperate.SelectedValue.ToNullaleInt();
                int? operatorid = ddlSearchOperator.SelectedValue.ToNullaleInt();
                int? mttypeid = ddlSearchMTType.SelectedValue.ToNullaleInt();
                int? routerid = ddlSearchRouter.SelectedValue.ToNullaleInt();
                grvData.DataSource = SmsShortCode.Paging(DB, currentPage, pageSize, ref totalRecord, txtSearchShortCode.Text.Trim(), cooperateid, operatorid, mttypeid, ddlSearchSmppAccount.SelectedValue, routerid);
                pagingtop.TotalRecord = pagingbottom.TotalRecord = totalRecord;
                pagingtop.Visible = pagingbottom.Visible = pagingtop.TotalPage > 1;
                grvData.DataBind();
                ltrInfo.Text = "Tổng cộng: " + totalRecord;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private void BindDropDownData()
        {
            var operatorList = DB.Operators.OrderBy(p => p.OrderID).ToList();
            BindDropDownListData(ddlSearchOperator, operatorList, "OperatorID", "OperatorName", new ListItem(""));
            BindDropDownListData(ddlOperator, operatorList, "OperatorID", "OperatorName", new ListItem(""));
            var cooperateList = DB.CooperateProviders.ToList();
            BindDropDownListData(ddlSearchCooperate, cooperateList, "CooperateID", "CooperateName", new ListItem(""));
            BindDropDownListData(ddlCooperate, cooperateList, "CooperateID", "CooperateName", new ListItem(""));
            var mttypeList = DB.SmsMTTypes.ToList();
            BindDropDownListData(ddlSearchMTType, mttypeList, "MTTypeID", "MTTypeCode", new ListItem(""));
            BindDropDownListData(ddlMTType, mttypeList, "MTTypeID", "MTTypeCode", new ListItem(""));
            var smppAccountList = DB.SmppAccounts.ToList();
            BindDropDownListData(ddlSearchSmppAccount, smppAccountList, "SmppID", "SmppAccount", new ListItem(""));
            BindDropDownListData(ddlSmppAccount, smppAccountList, "SmppID", "SmppAccount", new ListItem(""));
            var routerList = DB.SmsRouters.ToList();
            BindDropDownListData(ddlSearchRouter, routerList, "RouterID", "RouterName", new ListItem(""));
            BindDropDownListData(ddlRouter, routerList, "RouterID", "RouterName", new ListItem(""));
            BindDropDownListData(ddlMapShortCodeID, SmsShortCode.GetSmsShortCodeSource(), "ShortCodeID", "ShortCode", new ListItem(""));
        }
        
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
            BindGridData();
        }

        protected void tSortable_length_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                BindGridData();
            }
            catch { }
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int ID = Convert.ToInt32(e.CommandArgument);
                hdfID.Value = ID.ToString();
                switch (e.CommandName)
                {
                    case "Editing":
                        hdfAction.Value = "Editing";
                        SmsShortCode editObj = DB.SmsShortCodes.FirstOrDefault(p => p.ShortCodeID == ID);
                        if (editObj != null)
                        {
                            txtShortCode.Text = editObj.ShortCode;
                            ddlMapShortCodeID.SelectedValue = (editObj.MapShortCodeID ?? (object)"").ToString();
                            ddlCooperate.SetSelectedValue((editObj.CooperateID ?? (object)"").ToString());
                            ddlOperator.SetSelectedValue((editObj.OperatorID ?? (object)"").ToString());
                            ddlMTType.SetSelectedValue((editObj.MTTypeID ?? (object)"").ToString());
                            ddlSmppAccount.SetSelectedValue(editObj.SmppAccount ?? "");
                            ddlRouter.SetSelectedValue((editObj.RouterID ?? (object)"").ToString());
                            chkEnabled.Checked = editObj.Enabled ?? false;
                            chkAllowSentUnicode.Checked = editObj.AllowSentUnicode ?? false;
                            chkReplaceSimilarCharacter.Checked = editObj.ReplaceSimilarCharacter ?? false;
                            chkMORequired.Checked = editObj.MORequired ?? false;
                            chkApproveRequired.Checked = editObj.ApproveRequired ?? false;
                            chkMatchTemplateRequired.Checked = editObj.MatchTemplateRequired ?? false;
                            RegisterStartUpScript("OpenDialog('dialog1',600);");
                        }
                        break;
                    case "Deleting":
                        Authorize(Role.Write);
                        SmsShortCode deleteObj = DB.SmsShortCodes.FirstOrDefault(p => p.ShortCodeID == ID);
                        if (deleteObj != null)
                        {
                            DB.SmsShortCodes.DeleteOnSubmit(deleteObj);
                            DB.SubmitChanges();
                            InsertChangeLog("Xóa dữ liệu SmsShortCode");
                            BindGridData();
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                if (ValidateInfo())
                {
                    SmsShortCode obj;
                    if (hdfAction.Value == "Editing")
                        obj = DB.SmsShortCodes.FirstOrDefault(p => p.CooperateID == int.Parse(hdfID.Value));
                    else
                    {
                        obj = new SmsShortCode();
                    }
                    if (obj != null)
                    {
                        //Gán thuộc tính
                        obj.ShortCode = txtShortCode.Text.Trim();
                        obj.MapShortCodeID = ddlMapShortCodeID.SelectedValue.ToNullaleInt();
                        obj.CooperateID = ddlCooperate.SelectedValue.ToNullaleInt();
                        obj.OperatorID = ddlOperator.SelectedValue.ToNullaleInt();
                        obj.MTTypeID = ddlMTType.SelectedValue.ToNullaleInt();
                        obj.SmppAccount = ddlMTType.SelectedValue.ToNullIfNullOrEmpty();
                        obj.RouterID = ddlRouter.SelectedValue.ToNullaleInt();
                        obj.Enabled = chkEnabled.Checked;
                        obj.AllowSentUnicode = chkEnabled.Checked;
                        obj.ReplaceSimilarCharacter = chkReplaceSimilarCharacter.Checked;
                        obj.MORequired = chkMORequired.Checked;
                        obj.ApproveRequired = chkApproveRequired.Checked;
                        obj.MatchTemplateRequired = chkMatchTemplateRequired.Checked;
                        if (hdfAction.Value == "AddNew")
                        {
                            DB.SmsShortCodes.InsertOnSubmit(obj);
                        }
                        //save
                        DB.SubmitChanges();
                        //Ghi log tương tác
                        InsertChangeLog(hdfAction.Value == "Editing" ? string.Format("Cập nhật dữ liệu SmsShortCode, SmsShortCodeID: {0}", obj.ShortCodeID) : string.Format("Thêm mới dữ liệu SmsShortCode, SmsShortCodeID: {0}", obj.ShortCodeID));
                    }
                }
                BindGridData();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
    }
}